<?php

require_once 'Operations/Operation.php';

/**
 * Sends a log from the server to the client.
 */
class DownloadFile extends Operation {
	/**
	 * Sends a log from the server to the client.
	 */
	public function execute() {
		// Get user:
		$userFactory = new UserFactory();
		$user = $userFactory->getCurrent();
		
		// User must be authorized:
		if (!$user->isAuthorized()) {
			throw new PCException("Unauthorized user.", 403);
		}
		
		// Fetch needed data:
		$protocol = HTTPHandler::getGetParam("protocol");
		$account = HTTPHandler::getGetParam("account");
		$recipient = HTTPHandler::getGetParam("recipient");
		$startDate = HTTPHandler::getGetParam("startDate");
		
		// Check input:
		if (!$protocol or !$account or !$recipient or !$startDate) {
			throw new PCException("Missing protocol, account, recipient or startDate.", 400);
		}
		
		// Fetch the log:
		$log = ChatlogTable::get($user->getID(), $protocol, $account, $recipient, $startDate);
		if (!log) {
			throw new PCException("Unable to find specified chatlog.", 404);
		}
		
		// Display revision:
		HTTPHandler::setHeader("PCRevision", $log->getRevision());
		
		// Display contents:
		HTTPHandler::add($log->getContents());
		Logger::log("DownloadFile", "Log displayed.");
		
		// Log activity:
		$logData["protocol"] = $protocol;
		$logData["account"] = $account;
		$logData["recipient"] = $recipient;
		$logData["startDate"] = $startDate;
		$logData["revision"] = $log->getRevision();
		$logData["size"] = strlen($log->getContents());
		Database::logActivity("DownloadFile", $user->getID(), $user->getToken($_SERVER["REMOTE_ADDR"])->getTokenString(), serialize($logData));
	}
}